package kr.hkit.androidcomplete02.ch17;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class SaveStateEx extends Activity {
	MyView mv;
	int count;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setTitle("Count : " + count++);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		 mv = new MyView(this);
		if(savedInstanceState == null){
			mv.x = 50;
		}else{
			mv.x = savedInstanceState.getInt("x");
		}
		SharedPreferences pref = getSharedPreferences("SaveState", 0);
		mv.y = pref.getInt("y", 50);
		mv.setFocusable(true);
		mv.setFocusableInTouchMode(true);
		setContentView(mv);
	}
	
	//saveinstance에서 저장하면 activity가 실행되는 동안.
	//즉, 그 페이지 안에 머무는 동안만 저장됨.
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("x",mv.x);
	}
	
	//pause에서 저장하면 프로그램 종료되도 계속 저장하고 있음
	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences pref = getSharedPreferences("SaveState", 0);
		SharedPreferences.Editor edit = pref.edit();
		edit.putInt("y", mv.y);
		edit.commit();
	}
}

class MyView extends View{
	Paint p;
	int x, y;
	
	public MyView(Context context) {
		super(context);
		p = new Paint(Paint.ANTI_ALIAS_FLAG);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		p.setColor(Color.GREEN);
		canvas.drawCircle(x, y, 16, p);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			x = (int) (event.getX());
			y = (int) event.getY();
			invalidate();
			return true;
		}
		return false;
	}


}
